package com.cjm.concurrenttest;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 使用wait
 */
@Slf4j
public class TestWait {
    static final Object room = new Object();
    static boolean hasCigarette = false; //默认没烟
    static boolean hasTakeout = false;

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            synchronized (room) {
                if(!hasCigarette) {
                    log.debug("没烟，休息");
                    try {
                        room.wait(); //用notify好过interrupted
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if(hasCigarette) {
                    log.debug("有烟了 开始干活");
                }
            }
        },"xiao南").start();

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                synchronized (room){
                    log.debug("开始干活");
                }
            },"其他人").start();
        }

        TimeUnit.SECONDS.sleep(1);
        new Thread(() -> {
            synchronized (room) {
                hasCigarette = true;
                log.debug("烟到了");
                room.notify();
            }

        },"送烟").start();
    }

}
